package util;

import support.Constans;
import support.ObjectPoolSupport;
import support.RpcContext;
import support.RpcInfo;

import java.lang.reflect.Method;

public class AgentInvorker {
    public static RpcInfo invoke(Method method,RpcInfo rpcInfo){
        //从对象池取得实列对象
        String key = RpcContext.getInfoKeyByCall(rpcInfo);
       // String key = StringUtil.getSimpleName(rpcInfo.getClassName()) + "@" + rpcInfo.getMethodName(); //这里发过来的key应该是:com.xxx.接口名字
        RpcInfo resInfo = new RpcInfo();

        String metaInfo = RpcContext.getMetaInfo(key);
        if(metaInfo ==null){
            resInfo.setErrorCode("根据key找不到对应的元数据");
            return resInfo;
        }

        Class<?> aClass = null;
        try {
            aClass = Class.forName(metaInfo);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        if(ObjectPoolSupport.springSupport){
            ObjectPoolSupport poolSupport = ObjectPoolSupport.getContext().getBean(ObjectPoolSupport.class);

            try {
                Object objectForClassContex = poolSupport.getObjectForClassContex(aClass);
                Object res = method.invoke(objectForClassContex, rpcInfo.getArgs());
                resInfo.setCallRes(res);
            }catch (Exception e){
                e.printStackTrace();
                resInfo.setErrorCode(e.getMessage());
            }finally {
                return resInfo;
            }


        }else {
            Object object = RpcContext.objectPool.getObject(key);

            try {
                if (object == null) {
                    object = aClass.newInstance();
                    RpcContext.objectPool.putObject(key, object);
                }

                Object res = method.invoke(object, rpcInfo.getArgs());
                resInfo.setCallRes(res);
            } catch (Exception e) {
                e.printStackTrace();
                resInfo.setErrorCode(e.getMessage());
            } finally {
                return resInfo;
            }
        }
    }

}
